/*
 * Client.cpp
 *
 *  Created on: 09.12.2012
 *      Author: zheka
 */

#include "Client.hpp"

#include "util/ProxyException.hpp"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "util/StringUtils.hpp"
#include "util/Log.hpp"
#include <iostream>
Client::Client(ConnectionInfo connectionInfo) :
		connectionInfo(connectionInfo) {
}

void Client::connect() {

	connectionInfo.resolveHost();

	if ((socketFileDescriptor = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))
			== -1) {
		throw ProxyException("[Client] Can't create client socket!");
	}

	if (::connect(socketFileDescriptor, connectionInfo.getAddress(),
			connectionInfo.getAddressSize()) != 0) {
		throw ProxyException(
				"[Client] Can't connect to " + connectionInfo.getHost() + ":"
						+ StringUtils::toString(connectionInfo.getPort()));

	}
	Log::v("[Client] Connected to " + connectionInfo.getHostAddress());

	/*int optval = 1;
	int optlen = sizeof(optval);
	if (setsockopt(socketFileDescriptor, SOL_SOCKET, SO_KEEPALIVE, &optval,
			optlen) < 0) {

		throw ProxyException("[Client] Cant setopt!");
	}

	optval = 2000;

		if (setsockopt(socketFileDescriptor, SOL_SOCKET, 18, &optval,
				optlen) < 0) {

			throw ProxyException("[Client] Cant setopt!");
		}*/

}
int Client::getSocketFileDescriptor() {
	return socketFileDescriptor;
}
